package lc.q250_300;

public class Q300 {

    public static void main(String[] args) {
        Q300 q300 = new Q300();
        System.out.println(q300.lengthOfLIS2(new int[]{
                10,9,2,5,3,7,101,18
        }));
        System.out.println(q300.lengthOfLIS2(new int[]{
                0,1,0,3,2,3
        }));
        System.out.println(q300.lengthOfLIS2(new int[]{
                7,7,7,7,7,7,7
        }));
    }

    public int lengthOfLIS2(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int len = 1;
        int[] dp = new int[nums.length + 1];
        dp[len] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > dp[len]) {
                dp[len + 1] = nums[i];
                len ++;
            } else {
                // 查找并替换
                int l = 1, r = len, pos = 0;
                while (l <= r) {
                    int mid = (l + r) / 2;
                    if (dp[mid] < nums[i]) {
                        pos = mid;
                        l = mid + 1;
                    } else {
                        r = mid - 1;
                    }
                }
                dp[pos + 1] = nums[i];
            }
        }
        return len;
    }

    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            dp[i] = max(dp, nums, i);
        }
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (dp[i] > max) {
                max = dp[i];
            }
        }
        return max;
    }

    private int max(int[] dp, int[] nums, int i) {
        int result = 0;
        for (int j = 0; j < i; j++) {
            if (dp[j] > result && nums[i] > nums[j]) {
                result = dp[j];
            }
        }
        return result + 1;
    }
}
